<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
      >
        <el-form-item
          label="用户单位"
          :label-width="formLabelWidth"
          prop="userCompany"
        >
          <el-input v-model.trim="dataForm.userCompany" placeholder="用户单位">
          </el-input>
        </el-form-item>
        <el-form-item
          label="服务地点"
          :label-width="formLabelWidth"
          prop="serviceLocation"
        >
          <el-input
            v-model.trim="dataForm.serviceLocation"
            placeholder="服务地点"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="联系人"
          :label-width="formLabelWidth"
          prop="contactPerson"
        >
          <el-input v-model.trim="dataForm.contactPerson" placeholder="联系人">
          </el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
          <el-input v-model.trim="dataForm.phone" placeholder="电话">
          </el-input>
        </el-form-item>
        <el-form-item
          label="合同号"
          :label-width="formLabelWidth"
          prop="contractNumber"
        >
          <el-input v-model.trim="dataForm.contractNumber" placeholder="合同号">
          </el-input>
        </el-form-item>
        <el-form-item
          label="产品型号"
          :label-width="formLabelWidth"
          prop="productId"
        >
          <el-select
            v-model="dataForm.productId"
            clearable
            placeholder="请选择"
            @change="productModelChange"
          >
            <el-option
              v-for="item in productModelOptions"
              :key="item.id"
              :label="item.model"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="产品序号"
          :label-width="formLabelWidth"
          prop="exitNumber"
        >
          <el-input v-model.trim="dataForm.exitNumber" placeholder="产品序号">
          </el-input>
        </el-form-item>
        <el-form-item
          label="服务时间"
          :label-width="formLabelWidth"
          prop="serviceTime"
        >
          <el-date-picker
            v-model="dataForm.serviceTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择服务时间"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="服务人签字"
          :label-width="formLabelWidth"
          prop="serviceUser"
        >
          <el-input
            v-model.trim="dataForm.serviceUser"
            placeholder="服务人签字"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="服务内容"
          :label-width="formLabelWidth"
          prop="serviceContent"
        >
          <el-input
            type="textarea"
            v-model="dataForm.serviceContent"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="服务结果"
          :label-width="formLabelWidth"
          prop="serviceResult"
        >
          <el-input type="textarea" v-model="dataForm.serviceResult"></el-input>
        </el-form-item>
        <!-- <el-form-item label="附件" :label-width="formLabelWidth" prop="icon">
        <el-upload class="upload-demo" :action="url + '/file/uploadFileInterface'" :headers="headers"
          :before-upload="beforeAvatarUpload" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList"
          :on-success="handleSuccess" :on-change="handleChange">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item> -->
        <el-form-item label="附件" :label-width="formLabelWidth" prop="icon">
          <el-upload
            :action="url + '/file/uploadFileInterface'"
            list-type="picture-card"
            :headers="headers"
            :file-list="fileList"
            :on-success="handleSuccess"
            :on-change="handleChange"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownloadImg(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemoveImg(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false"
            >取 消</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="dataFormSubmit()"
            :disabled="isDisabled"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisibleImg"
      width="50%"
      style="height: 100%"
    >
      <div style="height: 60%">
        <img style="max-width: 100%" :src="dialogImageUrl" alt="" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import { getToken } from "@/utils/auth";
export default {
  emits: ["refreshDataList"],
  data() {
    let testPhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (value == "") {
        callback();
      } else if (!reg.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      dialogFormVisible: false,
      isDisabled: false,
      isval: false,
      isupdate: 0,
      istype: "",
      dataForm: {
        id: 0,
        userCompany: "", //用户单位
        serviceUser: "", //服务人签字
        serviceTime: "", //服务时间
        serviceResult: "", //服务结果
        serviceLocation: "", //服务地点
        serviceContent: "", //服务内容
        productModel: "", //产品型号
        productId: "",
        phone: "", //电话
        exitNumber: "", //产品序号
        contractNumber: "", //合同号
        contactPerson: "", //联系人
        appendixUrl: "", //附件路径
        appendixName: "", //附件名称
      },
      fileList: [],
      url: process.env.VUE_APP_BASE_API,
      headers: {
        token: getToken(), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      dialogVisibleImg: false,
      dialogImageUrl: "",
      productModelOptions: [],
      validRules: {
        driverName: [{ required: true, message: "司机姓名必填" }],
        driverPhone: [{ required: true, message: "司机联系电话必填" }],
        licenseNumber: [{ required: true, message: "车牌号必须填写" }],
      },
      deltableData: [],
      delAll: [],
      dataRule: {
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        phone: [{ validator: testPhone, trigger: "blur" }],
      },
      formLabelWidth: "120px",
      visible: false,
      // url: process.env.VUE_APP_BASE_API,
    };
  },
  created() {},
  methods: {
    async init(id) {
      this.dataForm.id = id || 0;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.productModel = "";
        this.fileList = [];
        this.productModelOptions = [];
        this.Sevice({
          url: "/product/list",
          method: "get",
        }).then(async (res) => {
          // console.log(res);
          if (res.code != 200) {
            // this.$message.error(res.data.msg)
          } else {
            this.productModelOptions = res.list;
          }
        });
        if (!this.dataForm.id) {
          // 新增
          // this.treeListTreeSetCurrentNode()
        } else {
          //获取详情
          this.Sevice({
            url: "/syn/maintenance/info/" + this.dataForm.id,
            method: "get",
          }).then(async (res) => {
            // console.log(res);
            if (res.code != 200) {
              // this.$message.error(res.data.msg)
            } else {
              this.dataForm.id = res.info.id;
              this.dataForm.userCompany = res.info.userCompany;
              this.dataForm.serviceUser = res.info.serviceUser;
              this.dataForm.serviceTime = res.info.serviceTime;
              this.dataForm.serviceResult = res.info.serviceResult;
              this.dataForm.serviceLocation = res.info.serviceLocation;
              this.dataForm.serviceContent = res.info.serviceContent;
              this.dataForm.productModel = res.info.productModel;

              this.dataForm.productId = res.info.productId;
              this.dataForm.phone = res.info.phone;
              this.dataForm.exitNumber = res.info.exitNumber;
              this.dataForm.contractNumber = res.info.contractNumber;
              this.dataForm.contactPerson = res.info.contactPerson;
              this.dataForm.appendixUrl = res.info.appendixUrl;
              this.dataForm.appendixName = res.info.appendixName;
              //附件
              if (this.dataForm.appendixUrl) {
                let appendixUrl = this.dataForm.appendixUrl.split(",");
                let appendixName = this.dataForm.appendixName.split(",");
                let list = [];
                for (let i = 0; i < appendixUrl.length; i++) {
                  list.push({
                    url: this.url + appendixUrl[i],
                    name: appendixName[i],
                    response: {
                      map: {
                        filePath: appendixUrl[i],
                        fileName: appendixName[i],
                      },
                    },
                  });
                }
                this.fileList = list;
              }
            }
          });
        }
      });
    },
    productModelChange(id) {
      for (let i = 0; i < this.productModelOptions.length; i++) {
        if (this.productModelOptions[i].id == id) {
          this.dataForm.productModel = this.productModelOptions[i].model;
        }
      }
    },
    handlePreview(file) {
      this.fileDown(file);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      let hz = file.name.split(".")[file.name.split(".").length - 1];
      // const isJPG = file.type === "image/jpg";

      //1MB=1024*1024(1MB=1024KB 1KB=1024MB)
      const is10M = file.size / 1024 / 1024 < 10;
      console.log(hz);
      //限制文件上传类型
      // if (hz!='obj') {
      // 	this.$message.error("只能上传obj格式的文件!");
      // 	return false
      // }

      return true;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.fileList = fileList;
      } else {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid == file.uid) {
            fileList.splice(i, 1);
          }
        }
        this.$message({ message: response.msg, type: "error", duration: 1000 });
      }
    },
    handleRemoveImg(file) {
      console.log(file, this.fileList);
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleDownloadImg(file) {
      console.log(file);
      this.getImge(file);
      this.fileDown(file);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    // 表单提交
    async dataFormSubmit() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          //附件
          let appendixUrl = [];
          let appendixName = [];
          console.log(this.fileList);
          if (this.fileList.length) {
            for (let i = 0; i < this.fileList.length; i++) {
              if (this.fileList[i].response) {
                appendixUrl.push(this.fileList[i].response.map.filePath);
              } else {
                appendixUrl.push(this.fileList[i].url);
              }
              appendixName.push(this.fileList[i].name);
            }
          }
          this.dataForm.appendixUrl = appendixUrl.toString();
          this.dataForm.appendixName = appendixName.toString();
          let url = this.dataForm.id
            ? "/syn/maintenance/update"
            : "/syn/maintenance/save";
          this.isDisabled = true;
          await this.Sevice({
            url: url,
            method: "post",
            data: {
              id: this.dataForm.id || undefined,
              appendixName: this.dataForm.appendixName,
              appendixUrl: this.dataForm.appendixUrl,
              contactPerson: this.dataForm.contactPerson,
              contractNumber: this.dataForm.contractNumber,
              exitNumber: this.dataForm.exitNumber,
              productId: this.dataForm.productId,
              productModel: this.dataForm.productModel,
              serviceContent: this.dataForm.serviceContent,
              serviceLocation: this.dataForm.serviceLocation,
              serviceResult: this.dataForm.serviceResult,
              serviceTime: this.dataForm.serviceTime,
              serviceUser: this.dataForm.serviceUser,
              userCompany: this.dataForm.userCompany,
              phone: this.dataForm.phone,
            },
          })
            .then((res) => {
              if (res && res.code == 200) {
                this.dialogFormVisible = false;
                this.$message({
                  message: res.msg,
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.isDisabled = false;
                    this.$emit("getMenuList");
                  },
                });
              } else {
                this.isDisabled = false;
              }
            })
            .catch((error) => {
              console.log(error);
              this.isDisabled = false;
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.mod-menu .menu-list__input > .el-input__inner,
.mod-menu .icon-list__input > .el-input__inner {
  cursor: pointer;
}

.mod-menu__icon-popover {
  width: 458px;
  overflow: hidden;
}

.mod-menu__icon-inner {
  width: 478px;
  max-height: 258px;
  overflow-x: hidden;
  overflow-y: auto;
}

.mod-menu__icon-list {
  width: 458px;
  padding: 0;
  margin: -8px 0 0 -8px;
}

.mod-menu__icon-list > .el-button {
  padding: 8px;
  margin: 8px 0 0 8px;
}

.mod-menu__icon-list > .el-button > span {
  display: inline-block;
  vertical-align: middle;
  width: 18px;
  height: 18px;
  font-size: 18px;
}

.mod-menu .icon-list__tips {
  font-size: 18px;
  text-align: center;
  color: #e6a23c;
  cursor: pointer;
}

.el-tree {
  height: 200px;
  overflow-y: auto;
}
</style>
